const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const cors = require('koa2-cors')
const path = require("path")
const { koaBody } = require("koa-body")
// 路由
const logger = require('./utils/logger')
const response = require('./utils/response')
// Swagger 文档
const Router = require('koa-router')
const router = new Router()
const setupSwagger = require('./config/swagger')
const setupRoutes = require('./config/routes');
const setupDb = require("./utils/db")
// 引入路由配置
const { koaBodyConfig } = require('./utils/utils')

// 添加这行引入Swagger配置
setupSwagger(router)
// 数据库连接
setupDb()
// 全局错误处理
app.use(async (ctx, next) => {
  try {
    await next()
  } catch (err) {
    console.log(err)
    ctx.status = err.status || 500
    response.error(ctx, {
      message: err.message || 'Internal Server Error',
      status: ctx.status
    })
    logger.error(`[Error] ${ctx.method} ${ctx.path} -> ${ctx.status} ${err.message}`)
  }
})

// 中间件
app
  .use(async (ctx, next) => {
    return koaBody(koaBodyConfig(ctx))(ctx, next)
  })
  .use(json())
  .use(router.routes())  // 确保这行在路由中间件之前
  .use(router.allowedMethods())
  .use(cors())
  .use(require('koa-static')(path.join(__dirname, 'public/attach')), {
    setHeaders: (res, path, stat) => {
      res.setHeader('Access-Control-Allow-Origin', '*');
      res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
      res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
      res.setHeader('Access-Control-Allow-Credentials', 'true');
      const isCacheable = /\.(css|js|jpe?g|png|gif|svg)$/i.test(path);
      if (isCacheable) {
        res.setHeader('Cache-Control', `public, max-age=${60 * 60 * 24 * 7}`);
        res.setHeader('Expires', new Date(Date.now() + 60 * 60 * 24 * 7 * 1000).toUTCString());
      }
    }
  })
  .use(require('koa-static')(path.join(__dirname, 'views/pay')))
  .use(views(path.join(__dirname, 'views'), {
    extension: 'html',
    map: { html: 'ejs' }
  }))

setupRoutes(app)
module.exports = app
